<?php
namespace app\index\controller;
use think\Controller;
use think\Config;

class Comment extends Controller {

	public function UploadComment () {

		$info = $_POST;
		$commentId = $info['id'];
		$comment = model('Comment');
		
		$res = array('code' => 0);
		if ($comment->where('id', $commentId)->find()) {

		} else {
			$comment->data([
				'openid' => $info['openid'],
				'food_id' => $info['food_id'],
				'comment_text' => $info['comment_text'],
				'score' => $info['score'],
				'avatar_url' => $info['avatar_url'],
				'nickname' => $info['nickname'],
				'comment_img1' => $info['comment_img1'],
				'comment_img2' => $info['comment_img2'],
				'comment_img3' => $info['comment_img3'],
			]);

			if ($comment->save()) {
				$res = array('code' => 1);
			}
		}

		// 更新菜品评论数量和分数
		$food = model('Food')->where('id', $info['food_id'])->find();
		$commentNum = $food->comment_num + 1;
		$score = ($food->star_score * $food->comment_num + $info['score']) / $commentNum;
		model('Food')->save(['comment_num' => $commentNum, 'star_score' => $score], ['id' => $info['food_id']]);

		echo json_encode($res);

		exit();
	}


	public function getCommentsByFoodId () {
		$foodId = $_POST['food_id'];
		$limit = $_POST['limit'];
		if ($limit == 0) {
			$res = model('Comment')->where('food_id', $foodId)->order('create_time', 'desc')->select();
		} else {
			$res = model('Comment')->where('food_id', $foodId)->order('create_time', 'desc')->limit($limit)->select();
		}

		$arr = array('code' => 0);

		if ($res) {
			$count = model('Comment')->where('food_id', $foodId)->count();
			$arr = array(
				'code' => 1,
				'data' => $res,
				'count' => $count
				);
		}

		echo json_encode($arr);
		exit();
	}



}